<?php

namespace App\Http\Controllers\Stock;

use App\Http\Controllers\ShopController;
use App\Models\Admin\Admin as AdminModel;
use App\Models\Config as ConfigModel;
use Illuminate\Support\Facades\Validator;

class AdminController extends ShopController
{
    public function login()
    {
        $code = request('code','');

        if(empty($code))
        {
            return $this->error('获取临时登录凭证失败');
        }

        $openid = $this->code2Session($code);

        if($openid === false)
        {
            return $this->error('获取登录凭证失败');
        }

        $admin = AdminModel::where(['openid' => $openid])->first();

        if(!$admin)
        {
            return $this->error('请先绑定账号',['openid' => $openid]);
        }

        if($admin['status'] !== 'normal')
        {
            return $this->error('账号已被禁用');
        }

        $data = [
            'id' => $admin['id'],
            'username' => $admin['username'],
            'nickname' => $admin['nickname'],
            'avatar_cdn' => $admin['avatar_cdn'],
            'avatar' => $admin['avatar'],
            'email' => $admin['email'],
            'mobile' => $admin['mobile'],
            'group_text' => $admin['group_text'],
            'createtime' => strtotime($admin['createtime'])
        ];

        return $this->success('登录成功',$data);
    }

    public function bind()
    {
        $username = request('username','');
        $password = request('password','');
        $openid = request('openid','');

        $admin = AdminModel::where(['username' => $username])->first();

        if(!$admin)
        {
            return $this->error('账号不存在');
        }

        $password = md5(md5($password) . $admin['salt']);

        if($password != $admin['password'])
        {
            return $this->error('密码错误');
        }

        if($admin['status'] !== 'normal')
        {
            return $this->error('账号已被禁用');
        }

        $admin->openid = $openid;

        $result = $admin->save();

        if($result === false)
        {
            return $this->error('绑定失败');
        }else{
            return $this->success('绑定成功');
        }
    }

    public function unbinding()
    {
        $admin = request()->get('admin');

        $admin->openid = null;

        $result = $admin->save();

        if($result === false)
        {
            return $this->error('解除微信绑定失败');
        }else{
            return $this->success('解除微信绑定成功');
        }
    }

    public function avatar()
    {
        $admin = request()->get('admin');

        // 查询url的值
        $url = ConfigModel::where(['name' => 'url'])->value('value');

        $url = $url . '/stock/admin/upload';
        
        // 第一个参数属于文件路径 第二个参数是文件类型 第三个是文件名
        $file =  new \CURLFile($_FILES['avatar']['tmp_name'],$_FILES['avatar']['type'],$_FILES['avatar']['name']);

        $res = httpRequest($url,['avatar' => $file,'adminid' => $admin->id]);

        $result = json_decode($res,true);

        if($result['code'] === 0)
        {
            return $this->error($result['msg']);
        }else{
            $admin = AdminModel::find($admin->id);

            $data = [
                'id' => $admin['id'],
                'username' => $admin['username'],
                'nickname' => $admin['nickname'],
                'avatar_cdn' => $admin['avatar_cdn'],
                'avatar' => $admin['avatar'],
                'email' => $admin['email'],
                'mobile' => $admin['mobile'],
                'group_text' => $admin['group_text'],
                'createtime' => strtotime($admin['createtime'])
            ];
    
            return $this->success($result['msg'],$data);
        }
    }

    public function profile()
    {
        $admin = request()->get('admin');

        $nickname = request('nickname','');
        $mobile = request('mobile','');
        $password = request('password','');
        $email = request('email','');

        // 封装
        $data = [
            'nickname' => $nickname,
            'mobile' => $mobile,
            'email' => $email
        ];

        // 处理密码
        if($password)
        {
            $repass = md5(md5($password) . $admin->salt);

            if($admin->password === $repass)
            {
                return $this->error('新密码与原密码一致');
            }

            $salt = build_randstr();

            $password = md5(md5($password) . $salt);

            $data['salt'] = $salt;
            $data['password'] = $password;
        }

        // 定义验证器
        $validate = [
            [
                'mobile' => ['required','unique:admin','regex:/^1[356789]\d{9}$/'],
                'nickname' => ['required'],
                'email' => ['required'],
            ],
            [
                'mobile.required' => '手机号必填',
                'mobile.unique' => '手机号已注册',
                'mobile.regex' => '手机号格式错误',
                'nickname.required' => '昵称必填',
                'email.required' => '邮箱必填',
            ]
        ];

        // 创建验证器
        $validator = Validator::make($data,...$validate);

        if($validator->fails())
        {
           return $this->error($validator->errors()->first());
        }

        $result = AdminModel::where(['id' => $admin->id])->update($data);

        if($result === false)
        {
            return $this->error('修改资料失败');
        }else{
            $admin = AdminModel::find($admin->id);

            $data = [
                'id' => $admin['id'],
                'username' => $admin['username'],
                'nickname' => $admin['nickname'],
                'avatar_cdn' => $admin['avatar_cdn'],
                'avatar' => $admin['avatar'],
                'email' => $admin['email'],
                'mobile' => $admin['mobile'],
                'group_text' => $admin['group_text'],
                'createtime' => strtotime($admin['createtime'])
            ];
            
            return $this->success('修改资料成功',$data);
        }
    }

    protected function code2Session($code)
    {
        $AppID = ConfigModel::where(['name' => 'AppID'])->value('value');

        $AppSecret = ConfigModel::where(['name' => 'AppSecret'])->value('value');

        $ApiUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=$AppID&secret=$AppSecret&js_code=$code&grant_type=authorization_code";

        $result = httpRequest($ApiUrl);

        $data = json_decode($result,true);

        $openid = $data['openid'] ?? '';

        if($openid)
        {
            return $openid;
        }else{
            return false;
        }

    }
}
